import { AssetManager, assetManager, director } from "cc";
import { tgxUIAlert } from "../../core_tgx/tgx";
import { ISubGame, getSubGameConf } from "./SubGameDef";
import { SceneUtil } from "../../core_tgx/base/SceneUtils";
import { GameMgr } from "./GameMgr";

export class SubGameMgr {
    private static _inst: SubGameMgr;
    public static get inst(): SubGameMgr {
        if (!this._inst) {
            this._inst = new SubGameMgr();
        }
        return this._inst;
    }

    public static current: ISubGame;
    public static gameMgr: GameMgr;

    private _gameMgrMap = {};

    public async loadSubGame(subgameId: string, loadEntryScene?: boolean) {
        this.unloadCurrent();

        if (subgameId) {
            let conf = getSubGameConf(subgameId);
            if (!conf) {
                tgxUIAlert.show("can't find subgame:" + subgameId);
                return;
            }

            SubGameMgr.current = conf;
            await this.loadBundleSync(conf.entry.bundle);

            if (loadEntryScene) {
                SceneUtil.loadScene(conf.entry);
            }
        }
    }

    private loadBundleSync(bundleName: string) {
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(bundleName, (err, bundle: AssetManager.Bundle) => {
                resolve(!err);
            });
        });
    }

    public unloadSubGame(conf: ISubGame) {
        if (!conf) {
            return;
        }
        let bundle = assetManager.getBundle(conf.entry.bundle);
        if (bundle) {
            bundle.releaseAll();
            assetManager.removeBundle(bundle);
        }
    }

    public unloadCurrent() {
        if (SubGameMgr.current) {
            this.unloadSubGame(SubGameMgr.current);
            SubGameMgr.current = null;
        }
    }

    public registerGameMgr(type: string, gameMgr: GameMgr) {
        this._gameMgrMap[type] = gameMgr;
    }

    public getGameMgr(type: string): GameMgr {
        return this._gameMgrMap[type];
    }
}